import React, { useState, useEffect, Fragment } from 'react'
import { Table, Row, Col, Layout } from 'antd';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import FlowGraph from './Graph'
import ToolBar from './components/ToolBar'
import ConfigPanel from './components/ConfigPanel'
import '../reset.less'
import '../global.css'
import styles from './index.less'
// @ts-ignore
import reqwest from 'reqwest'
import classnames from 'classnames'

const { Content, Sider } = Layout;

//表格头
const inferenceResultColumn = [{
  key: 'name',
  title: '名称',
  dataIndex: 'name',
}, {
  key: 'confidence',
  title: '分数',
  dataIndex: 'confidence',
}, {
  key: 'download',
  title: '下载',
  dataIndex: 'download',
  render: (text: any, record: any, index: any) => {
    return <a onClick={(e) => { return downloadInferenceResult(record) }}>下载</a>
  }
}]

const downloadInferenceResult = (record: any) => {

  FlowGraph.graph.toPNG((datauri: string) => {
    let data = JSON.stringify({ inference_id: FlowGraph.inferenceDialogData.id, inference_result_id: record.id, malfunction_id: FlowGraph.inferenceDialogData.malfunction_id, png: datauri.split(",")[1] });
    let input = "<input type='hidden' name='data' value='" + data + "' />";
    // request发送请求
    // @ts-ignore
    top.jQuery('<form action="/OMDS/api/rest/inference/result/download" method="post">' + input + '</form>').appendTo('body').submit();
    // top.$.ajax({
    //   type: 'post',
    //   data: { data: JSON.stringify({ inference_id: FlowGraph.inferenceDialogData.id, inference_result_id: record.id, malfunction_id: FlowGraph.inferenceDialogData.malfunction_id, png: datauri.split(",")[1] }) },
    //   url: '/OMDS/api/rest/inference/result/download',
    //   success: function (res: any) {
    //     console.log(res);
    //     if (res.code == 200) {
    //       //初始化页面，显示总的故障树图
    //     } else {
    //       // @ts-ignore
    //       top.MSG.error("下载推理结果失败！请稍后再试")
    //     }
    //   }
    // })
  })
}

//表格头
const feedbackColumn = [
  //   {
  //   key: 'text',
  //   title: '推理任务名称',
  //   dataIndex: 'text',
  //   ellipsis: true,
  //   width: 150
  // }, 
  {
    key: 'name',
    title: '结果名称',
    dataIndex: 'name',
    ellipsis: true,
    width: 200
  }, {
    // key: 'msg',
    key: 'score',
    // title: '反馈信息',
    title: '分数',
    // dataIndex: 'msg',
    dataIndex: 'score',
    ellipsis: true,
    width: 100
  }]

//推理报告界面，推理结果列表
const defaultInferenceResultData = [{
  key: '1',
  name: '推理结果1',
  score: '98',
  node_id: ["bd739839-9072-4ac5-bf39-55df708b2baa", "359b4565-5ed4-40c4-8c79-390c711b55e5", "0627fbce-9703-4ee1-8342-e327c593126e", "a68f7359-e770-44d2-ad9a-b17259c8b02f", "a15104d6-8e6e-4dec-bb26-490bc123eb1e", "d02f5891-6a65-4be6-a5f9-df9b42371ea2", "a293fa6b-c4e0-4196-8964-1f3dc00dc15f", "824274dc-8bb1-42cf-b222-9bc1000a837e", "69816eb7-965d-4fb3-b0bd-d6276f93372d", "182534b7-aeac-492b-948d-aa6cfcdca4ad"]
}, {
  key: '2',
  name: '推理结果2',
  score: '96',
  node_id: ["bd739839-9072-4ac5-bf39-55df708b2baa", "151f0f4e-4c5d-400f-9837-30c2d7bdd013", "a68f7359-e770-44d2-ad9a-b17259c8b02f", "a15104d6-8e6e-4dec-bb26-490bc123eb1e", "d02f5891-6a65-4be6-a5f9-df9b42371ea2", "a293fa6b-c4e0-4196-8964-1f3dc00dc15f", "824274dc-8bb1-42cf-b222-9bc1000a837e", "69816eb7-965d-4fb3-b0bd-d6276f93372d", "182534b7-aeac-492b-948d-aa6cfcdca4ad"]
}, {
  key: '3',
  name: '推理结果3',
  score: '90',
  node_id: ["bd739839-9072-4ac5-bf39-55df708b2baa", "696fe8bb-cad8-4eee-8d37-1ac6e4e7ae44", "68842fbf-c9cd-4021-99a6-8e5b3e5ac4a2", "a68f7359-e770-44d2-ad9a-b17259c8b02f", "a15104d6-8e6e-4dec-bb26-490bc123eb1e", "d02f5891-6a65-4be6-a5f9-df9b42371ea2", "a293fa6b-c4e0-4196-8964-1f3dc00dc15f", "824274dc-8bb1-42cf-b222-9bc1000a837e", "69816eb7-965d-4fb3-b0bd-d6276f93372d", "182534b7-aeac-492b-948d-aa6cfcdca4ad"]
}]

//模拟专家订正界面，用户反馈数据
const defaultFeedbackData = [{
  key: '1',
  name: '推理结果1',
  result: '错误',
}, {
  key: '2',
  name: '推理结果2',
  result: '错误',
}, {
  key: '3',
  name: '推理结果3',
  result: '错误',
}]

//获取url拼接的参数（类型）
const getParameter = (C: any) => {  // 获取url参数
  let B = location.href;
  let E = B.substring(B.indexOf("?") + 1, B.length).split("&");
  let A: any = {};
  let j = "";
  for (let D = 0; j = E[D]; D++) {
    A[j.substring(0, j.indexOf("="))] = j.substring(j.indexOf("=") + 1, j.length)
  }
  let F = A[C];
  if (typeof (F) == "undefined") {
    return ""
  } else {
    return F
  }
  return F
}

export default function () {
  const [isReady, setIsReady] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([])
  const [graph, setGraph] = useState<any>(null)
  const [pageType, setPageType] = useState<any>(getParameter("pageType"))
  const [inferenceResultData, setInferenceResultData] = useState<any[]>([])
  const [edges, setEdges] = useState<any[]>([]) // 总图里面的连线
  const [nodes, setNodes] = useState<any[]>([]) // 总图里面的节点
  const [assessmentScore, setAssessmentScore] = useState<any>("") // 评估置信度
  const [feedbackData, setFeedbackData] = useState<any[]>([])
  const [resultData, setResultData] = useState<any[]>([]) // 质量检测的节点result数据
  const [messageRowDisplay, setMessageRowDisplay] = useState("none")
  const [leftSiderCollapsed, setLeftSiderCollapsed] = useState(false)
  const [rightSiderCollapsed, setRightSiderCollapsed] = useState(true)

  const getContainerSize = () => {
    let width = 581;
    let height = 38;
    if (pageType == "2") {
      height = 246;
    }
    return {
      width: document.body.offsetWidth - width,
      height: document.body.offsetHeight - height,
    }
  }

  useEffect(() => {
    FlowGraph.pageType = pageType;
    const graph = FlowGraph.init()
    setIsReady(true)
    setGraph(graph)

    if (pageType) {
      if (pageType == "1") {
        getInferenceResultData(true);
      }
      if (pageType == "2") {
        getResultList();
        setMessageRowDisplay("")
        FlowGraph.reloadFeedback = reloadFeedback;
      }
    }

    const resizeFn = () => {
      const { width, height } = getContainerSize()
      graph.resize(width, height)
    }
    resizeFn()

    window.addEventListener('resize', resizeFn)
    return () => {
      window.removeEventListener('resize', resizeFn)
    }

  }, [])

  const getInferenceResultData = (isLoadGraph: boolean) => { // 获取推理结果列表
    if (isLoadGraph)
      setSelectedRowKeys([])
    // @ts-ignore
    let showId = top.DIALOG.showIds.top()
    // @ts-ignore
    let inferenceDialogData = top.DIALOG.get(showId).state.data
    let formData = inferenceDialogData
    FlowGraph.inferenceDialogData = inferenceDialogData
    reqwest({
      method: 'post',
      data: { data: JSON.stringify(formData) },
      url: '/OMDS/api/rest/inference/result/getResultData',
      success: function (res: any) {
        if (res.code == 200) {
          //初始化页面，显示总的故障树图
          if (res.data) {
            setInferenceResultData(res.data.result)
            let newData = JSON.parse(JSON.stringify(res.data.result));
            newData.map((item: any) => {
              item.defaultConfidence = item.confidence; // 复制一份推理结果分数，做初始分数
            });
            FlowGraph.inferenceResultData = newData;
            // if (inferenceDialogData.malfunction_id) {
            //   try {
            //     FlowGraph.initGraphShape(isLoadGraph)
            //   } catch (e) { }
            // }
          }
        } else {
          // @ts-ignore
          top.MSG.error("获取推理结果列表失败！请稍后再试")
        }
      }
    })

  }

  const getResultList = () => {
    // let res1 = { code: 200, data: "{\"151f0f4e-4c5d-400f-9837-30c2d7bdd013\":\"1\",\"a68f7359-e770-44d2-ad9a-b17259c8b02f\":\"1\"}" }
    // @ts-ignore
    let showId = top.DIALOG.showIds.top()
    // @ts-ignore
    let data = top.DIALOG.get(showId).state.data
    let formData = {
      id: data.id,
      malId: data.malId
    }
    FlowGraph.feedbackDialogData = data;

    reqwest({
      method: 'post',
      data: { data: JSON.stringify(formData) },
      url: '/OMDS/api/rest/quality/getResultData',
      success: function (res: any) {
        if (res.code == 200) {
          //设置置信度分数
          setAssessmentScore(res.data.smartValue);
          // setFeedbackData(res.data.msg)
          FlowGraph.msgList = res.data.msg

          let feedback = res.data.feedBack;
          if (feedback && feedback.length > 0) {
            FlowGraph.feedbackData = feedback;
          }
        } else {
          // @ts-ignore
          top.MSG.error("获取推理结果列表失败！请稍后再试")
        }
      }
    })
  }

  const reloadFeedback = (graph: any) => {

    if (FlowGraph.feedbackDialogData) {
      let desnode = graph.getCellById(FlowGraph.feedbackDialogData.desnodeid) || {};
      let desnodedata = desnode.data;
      if (desnodedata) {
        setFeedbackData([{ name: desnodedata.text, score: desnodedata.score }])
      }
    }
  }

  const resetGraph = () => {
    setSelectedRowKeys([]) // 清空表格选择行

    FlowGraph.initGraphShape(true)
    FlowGraph.inferenceRecord = undefined
    FlowGraph.inferenceId = undefined
  }

  const handleRowClassName = (record: any, index: any) => {
    let rowClassName = "";
    if (selectedRowKeys && selectedRowKeys.indexOf(record.key) !== -1) {
      rowClassName = "ant-table-row-selected";
    }
    return rowClassName;
  }

  const handleRowClick = (record: any, e: any) => { // 点击表格
    setSelectedRowKeys([record.key])
    if (graph) {
      let node_id = record.node_id;
      if (typeof (node_id) == "string") {
        node_id = JSON.parse(node_id)
      }
      FlowGraph.inferenceRecord = record
      FlowGraph.inferenceId = record.id

      if (node_id) {
        FlowGraph.getContentCells(node_id)
      }
    }
  }

  const handleCellClick = (cellId: any, cell: any) => {
    if (cellId) {
      setRightSiderCollapsed(false);
      let feedbackData: any = [];
      let data = cell.data;
      let id = data ? data.id : "";
      let name = data ? data.text : "";
      let type = data ? data.type : "";
      // FlowGraph.feedbackData.map((item: any) => {
      //   let result = "";
      //   let msg = "未反馈";
      //   if (item.feedback && item.feedback != "null") {
      //     let feedback = JSON.parse(item.feedback);
      //     result = feedback[id];
      //   }
      //   if (result == "1") {
      //     msg = type == "1" ? "已执行" : "正确"
      //     feedbackData.push({ text: item.text, name: name, msg: msg })

      //   } else if (result == "0") {
      //     msg = type == "1" ? "未执行" : "错误"
      //     feedbackData.push({ text: item.text, name: name, msg: msg })
      //   }
      // })
      // //设置专家订正页面用户反馈信息
      // setFeedbackData(feedbackData);
      if (data) {
        setFeedbackData([{ name: data.text, score: data.score }])
      }
    } else {
      if (pageType == "2") {
        setRightSiderCollapsed(true);
      } else {
        setRightSiderCollapsed(false);
      }
      // setFeedbackData(FlowGraph.msgList);
      reloadFeedback(FlowGraph.graph)
    }
  }

  const handleRightCollapse = (collapsed: any, type: any) => {
    setRightSiderCollapsed(collapsed);
  }

  const handleLeftCollapse = (collapsed: any, type: any) => {
    setLeftSiderCollapsed(collapsed);
  }

  return (
    <Layout className={styles.wrap}>
      {/* <div className={styles.header}>
        <span>故障树配置</span>
      </div>*/
      }
      <Layout className={styles.content}>
        {
          pageType == "1" ?
            <Sider className={styles.sider} width="290" theme="light" collapsible={true} collapsedWidth={0} collapsed={leftSiderCollapsed} onCollapse={handleLeftCollapse}
              trigger={leftSiderCollapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}>
              <div id="inferenceResult" className={styles.inferenceResult}>
                <div className={styles.title}>
                  推理结果列表
                  <a className={styles.reset} onClick={resetGraph}>重置</a>
                </div>
                <div className={styles.table}>
                  <Table columns={inferenceResultColumn} dataSource={inferenceResultData} size='small' showHeader={false} bordered pagination={{ pageSize: 3, hideOnSinglePage: true, total: inferenceResultData.length, showSizeChanger: false, showQuickJumper: false }} rowClassName={handleRowClassName} onRow={record => {
                    return {
                      onClick: (e) => { return handleRowClick(record, e) } // 点击行
                    };
                  }}></Table>
                </div>
              </div>
              <div id="stencil" className={styles.stencil} />
            </Sider> : <Sider width="290" theme="light" collapsible={true} collapsedWidth={0} collapsed={leftSiderCollapsed} onCollapse={handleLeftCollapse}
              trigger={leftSiderCollapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}><div id="stencil" className={styles.sider} /></Sider>
        }
        <Content className={styles.panel}>
          <div className={styles.toolbar}>{isReady && <ToolBar reloadResultTable={getInferenceResultData} />}</div>
          {
            pageType == "2" ? <Fragment>
              <div id="container" className={classnames("x6-graph", styles.container)} />
              <Row className={styles.messageRow} style={{ display: messageRowDisplay }}>
                <Col className={styles.messageDiv} span={5}>
                  <div className={styles.title}>智能评估信息</div>
                  <div>评估置信度：{assessmentScore}</div>
                </Col>
                <Col className={styles.messageDiv} span={19}>
                  <div className={styles.title}>用户反馈信息</div>
                  <div className={styles.table}>
                    <Table columns={feedbackColumn} dataSource={feedbackData} size='small' showHeader={false} bordered pagination={{ pageSize: 3, hideOnSinglePage: true, total: feedbackData.length, showSizeChanger: false, showQuickJumper: false }} ></Table>
                  </div>
                </Col>
              </Row>
            </Fragment>
              : <div id="container" className={classnames("x6-graph", styles.container)} />
          }
        </Content>
        <Sider className={styles.config} width="290" theme="light" collapsible={true} collapsedWidth={0} reverseArrow={true} collapsed={rightSiderCollapsed} style={{ padding: rightSiderCollapsed ? 0 : "0 14px" }} onCollapse={handleRightCollapse}
          trigger={rightSiderCollapsed ? <MenuFoldOutlined /> : <MenuUnfoldOutlined />}
        >
          {isReady && <ConfigPanel onCellClick={handleCellClick} />}
        </Sider>
      </Layout>
    </Layout>
  )
}
